import React from 'react';
import { Input, Form, Radio, Select, Cascader, Switch, DatePicker, message } from 'antd';
import { useMemo, useState, useEffect } from 'react';

import { SvgIcon } from '@/components/icon';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useTranslation } from 'react-i18next';
import { useDatasetStore } from '@/store/datasetStore';
import { DatasetTypeEnum } from '@/common';
// import './../../../styles/know-gov.scss';
import dayjs from 'dayjs';
import { useLocation } from 'react-router-dom';
import Modals from '@/components/modals/Modals';
import TextArea from '@/components/Antd/TextArea';

interface DeleteConfirmModalProps {
  visible: boolean;

  onCancel: () => void;
  onConfirm: (onItem: any) => void;
  onItem?: any;
  title: string;
  isErr: string;
  treeData?: any[];
}

interface Option {
  key: string;
  value: string | number;
  label: React.ReactNode;
  name: string;
  children?: Option[];

  type: string;
  disabled?: boolean;
}

const icons: Record<string, React.ReactNode> = {
  dataset: <SvgIcon icon="mdi--folder-zip" size={20} />,
  folder: <SvgIcon icon="ri--folder-2-fill" size={20} />,
  faq: <SvgIcon icon="mdi--folder-zip" size={20} />,
};

type RequiredMark = boolean | 'optional' | 'customize';

const connectorAddModal: React.FC<DeleteConfirmModalProps> = ({
  visible,
  onCancel,
  onConfirm,
  onItem,
  title,
  isErr,
  treeData,
}) => {
  const { allDatasets, expandedKeys, loadCollections, loadAllDatasets } = useDatasetStore();

  const [messageApi, contextHolder] = message.useMessage();

  const [options, setOptions] = useState<Option[]>([]);

  const { SHOW_CHILD } = Cascader;

  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const appId = queryParams.get('appId') || '';

  useEffect(() => {
    form.resetFields();
  }, [onItem]);

  useEffect(() => {
    if (treeData) {
      const result = treeData.filter((item) => item.type !== 'function');
      setOptions(generateOptions(result.filter((item) => item.type != DatasetTypeEnum.api)));
    }
  }, [treeData]);

  const generateOptions = (datasets: any[]) => {
    return datasets.map((dataset) => {
      const option: Option = {
        key: dataset._id,
        value: dataset._id,
        label: (
          <div className="inline-block" style={{ verticalAlign: 'middle' }}>
            <div className="flex items-center self-center">
              {icons[dataset.type]} <span className="ml-1">{dataset.name}</span>
            </div>
          </div>
        ),
        name: dataset.name,
        children: dataset.children ? generateOptions(dataset.children) : undefined,
        type: dataset.type,
        // disabled:dataset.type =="folder" ? true : false,
      };
      return option;
    });
  };

  const filter = (inputValue: string, path: Option[]) => {
    return path.some(
      (option) =>
        option?.name?.toString().includes(inputValue) ||
        (option &&
          option.children &&
          option?.children?.filter((c) => c.name.toString().includes(inputValue)).length > 0),
    );
  };

  const loadDatasets = async () => {
    try {
      // setDataLoading(true);
      await loadAllDatasets({
        parentId: '',
        app_id: appId,
      });
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    // 获取知识库
    loadDatasets();
  }, []);

  const dataType = useMemo(() => {
    return allDatasets.map((item: any) => {
      return {
        label: item.name,
        value: item._id,
      };
    });
  }, [allDatasets]);

  const [form] = Form.useForm();

  const [radioValue, setRadioValue] = useState('web');
  const [cron, setCron] = useState('manual');
  const [datasetCreateType, setDatasetCreateType] = useState('manual');

  const onRadio = (e: any) => {
    setRadioValue(e.target.value);
  };

  const onCronChanged = (taskType: string) => {
    setCron(taskType);
  };

  const onDatasetCreateTypeChanged = (datasetCreateType: string) => {
    setDatasetCreateType(datasetCreateType);
  };

  useEffect(() => {
    const processedUrls = Array.isArray(onItem.urls) ? onItem.urls.join('\n') : onItem.urls;
    const datasetIdArr = onItem.tree;

    // 处理 clockTime 转换
    const processedClockTime = onItem.clockTime ? dayjs(onItem.clockTime) : null;

    form.setFieldsValue({
      ...onItem,
      urls: processedUrls, // 设置 urls 为换行字符串
      datasetId: datasetIdArr,
      clockTime: processedClockTime,
      depth: onItem.depth === 1,
      feishuAppId: onItem.feishuAppId || '',
      feishuAppSecret: onItem.feishuAppSecret || '',
      forceSync: onItem.forceSync || false,
    });

    setRadioValue(onItem?.type);
    setDatasetCreateType(onItem?.datasetCreateType);
  }, [onItem, form]);

  const handleSumit = async () => {
    try {
      const values = await form.validateFields();
      console.log('form.validateFields()===========', values);
      onConfirm(values);
    } catch (errorInfo) {
      console.error('Validation failed:', errorInfo);
    }
  };

  return (
    <>
      {contextHolder}
      <Modals open={visible} onCancel={onCancel} onOk={handleSumit} title={title}>
        <div
          style={{
            display: 'flex',
            flexDirection: 'column',
            margin: '10px 0px',
          }}
        >
          <Form form={form} layout="vertical" initialValues={onItem} className="form-item-space">
            <Form.Item label="数据类型" name="type">
              <Radio.Group
                defaultValue={'web'}
                value={radioValue}
                onChange={onRadio}
                options={[
                  // { value: 'file', label: '文件' },
                  { value: 'web', label: '网页' },
                  { value: 'feishu', label: '飞书文档' },
                  // { value: 'api', label: 'API' },
                  // { value: 'database', label: '数据库' },
                ]}
              ></Radio.Group>
            </Form.Item>

            {radioValue == 'file' && (
              <>
                {isErr == 'file' && (
                  <div style={{ position: 'absolute', right: '24px', color: '#FF4C40' }}>
                    {'该接口不符合平台格式要求'}
                  </div>
                )}

                <Form.Item label="文件地址" name="urls">
                  <Input.TextArea
                    rows={5}
                    style={{
                      borderColor: isErr == 'file' ? '#FF4C40' : 'white',
                    }}
                    className="!bg-input-gray"
                    placeholder="请输入或粘贴（多个地址换行输入）. . ."
                  />
                </Form.Item>
              </>
            )}
            {radioValue == 'feishu' && (
              <>
                {isErr == 'feishu' && (
                  <div style={{ position: 'absolute', right: '24px', color: '#FF4C40' }}>
                    {'该接口不符合平台格式要求'}
                  </div>
                )}

                <Form.Item
                  label="飞书链接"
                  name="urls"
                  rules={[{ required: true, message: '请输入飞书链接' }]}
                >
                  <Input.TextArea
                    disabled={title === '编辑'}
                    rows={5}
                    style={{
                      borderColor: isErr == 'feishu' ? '#FF4C40' : 'white',
                    }}
                    className="!bg-input-gray"
                    placeholder="支持填写飞书文档、飞书文件夹、飞书知识库链接（对外的链接形式）"
                  />
                </Form.Item>
                <Form.Item
                  label="appId"
                  name="feishuAppId"
                  rules={[{ required: true, message: '请输入飞书appId' }]}
                >
                  <Input placeholder="请输入或粘贴" className="!bg-input-gray" />
                </Form.Item>
                <Form.Item
                  label="appSecret"
                  name="feishuAppSecret"
                  rules={[{ required: true, message: '请输入飞书appSecret' }]}
                >
                  <Input placeholder="请输入或粘贴" className="!bg-input-gray" />
                </Form.Item>
              </>
            )}
            {radioValue === 'web' && (
              <>
                {isErr == 'web' && (
                  <div style={{ position: 'absolute', right: '24px', color: '#FF4C40' }}>
                    {'该接口不符合平台格式要求'}
                  </div>
                )}
                <Form.Item
                  label="网页地址"
                  name="urls"
                  rules={[{ required: true, message: '请输入地址' }]}
                >
                  <TextArea
                    rows={5}
                    style={{
                      // backgroundColor: '#ECEFF8',
                      borderColor: isErr == 'web' ? '#FF4C40' : 'white',
                    }}
                    disabled={title === '编辑'}
                    // className="!bg-input-gray"
                    bg
                    placeholder="请输入或粘贴（多个地址换行输入）. . ."
                  />
                </Form.Item>
              </>
            )}

            {radioValue === 'api' && (
              <>
                {isErr == 'api' && (
                  <div style={{ position: 'absolute', right: '24px', color: '#FF4C40' }}>
                    {'该接口不符合平台格式要求'}
                  </div>
                )}
                <Form.Item label="API地址" name="urls">
                  <Input.TextArea
                    rows={5}
                    style={{
                      // backgroundColor: '#ECEFF8',
                      borderColor: isErr == 'api' ? '#FF4C40' : 'white',
                    }}
                    className="!bg-input-gray"
                    placeholder="请输入或粘贴（多个地址换行输入）. . ."
                  />
                </Form.Item>
                <Form.Item label="API KEY" name="apiKey">
                  <Input
                    style={{
                      // backgroundColor: '#ECEFF8',
                      borderColor: isErr == 'api' ? '#FF4C40' : 'white',
                    }}
                    className="!bg-input-gray"
                    placeholder="请输入API KEY"
                  />
                </Form.Item>
                <Form.Item label="API类型" name="apiType">
                  <Select
                    className="!rounded-default !bg-input-gray"
                    style={{ border: 'none' }}
                    bordered={false}
                    onChange={handleChange}
                    options={[
                      { value: 'add', label: '新增' },
                      { value: 'update', label: '更新' },
                      { value: 'delete', label: '删除' },
                    ]}
                  />
                </Form.Item>
                <Form.Item label="资源类型" name="resourceType">
                  <Select
                    className="!rounded-default !bg-input-gray"
                    style={{ border: 'none' }}
                    bordered={false}
                    onChange={handleChange}
                    options={[
                      { value: 'file', label: '文件' },
                      { value: 'content', label: '数据块' },
                    ]}
                  />
                </Form.Item>
              </>
            )}

            {radioValue === 'database' && (
              <div>
                <Form.Item label="数据库类型" name="databaseType">
                  <Select
                    // className="!rounded-default !bg-input-gray"
                    className="!rounded-default !bg-input-gray"
                    style={{ border: 'none' }}
                    bordered={false}
                    defaultValue="mysql"
                    onChange={handleChange}
                    options={[{ value: 'mysql', label: 'mysql' }]}
                  />
                </Form.Item>
                {isErr == 'database' && (
                  <div style={{ position: 'absolute', right: '24px', color: '#FF4C40' }}>
                    {'通过该字符串和SQL语句未查询到数据'}
                  </div>
                )}
                <Form.Item label="连接字符串" name="link">
                  <Input.TextArea
                    rows={5}
                    className="!bg-input-gray"
                    style={{
                      // backgroundColor: '#ECEFF8',
                      borderColor: isErr == 'database' ? '#FF4C40' : 'white',
                    }}
                    placeholder="请输入或粘贴 . . ."
                  />
                </Form.Item>
                <Form.Item label="SQL语句" name="sql">
                  <Input.TextArea
                    rows={5}
                    className="!bg-input-gray"
                    style={{
                      // backgroundColor: '#ECEFF8',
                      borderColor: isErr == 'database' ? '#FF4C40' : 'white',
                    }}
                    placeholder="请输入或粘贴 . . ."
                  />
                </Form.Item>
              </div>
            )}

            <Form.Item
              label="更新频率"
              name="cron"
              rules={[{ required: true, message: '请选择更新频率' }]}
            >
              <Radio.Group
                // defaultValue={'file'}
                // value={radioValue}
                onChange={(e) => {
                  onCronChanged(e.target.value);
                }}
                options={[
                  { value: 'manual', label: '不自动更新' },
                  { value: 'everyday', label: '每天' },
                  { value: 'every3day', label: '3天' },
                  { value: 'every7day', label: '7天' },
                ]}
              ></Radio.Group>
            </Form.Item>

            {radioValue === 'api' && (
              <Form.Item label="知识库配置" name="datasetCreateType">
                <Radio.Group
                  onChange={(e) => {
                    onDatasetCreateTypeChanged(e.target.value);
                  }}
                  options={[
                    { value: 'manual', label: '选择知识库' },
                    { value: 'metadata', label: '使用metadata自动生成知识库' },
                  ]}
                ></Radio.Group>
              </Form.Item>
            )}

            {/* {radioValue !== 'api' ||
            (radioValue === 'api' && datasetCreateType === 'manual' && (
              <Form.Item label="知识库" name="datasetId">
                <Select
                  // defaultValue={dataType[0]}
                  className="selectborder"
                  // onChange={handleChange}
                  options={dataType}
                  placeholder="请选择知识库"
                />
              </Form.Item>
            ))} */}

            <Form.Item name="clockTime" label="更新时间">
              <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" className="!bg-input-gray" />
            </Form.Item>

            {radioValue === 'web' && (
              <Form.Item layout="horizontal" label="深度爬取" name="depth">
                <Switch checkedChildren="开启" unCheckedChildren="关闭" />
              </Form.Item>
            )}
            {radioValue === 'feishu' && (
              <Form.Item layout="horizontal" label="全量更新" name="forceSync">
                <Switch checkedChildren="开启" unCheckedChildren="关闭" />
              </Form.Item>
            )}

            <Form.Item
              label="知识库"
              name="datasetId"
              rules={[{ required: true, message: '请选择知识库' }]}
            >
              {/* <Select
              // defaultValue={dataType[0]}
              className="selectborder"
              // onChange={handleChange}
              options={dataType}
              placeholder="请选择知识库"
            /> */}
              <Cascader
                // className="share-link-cascader"
                // className="!rounded-default !bg-input-gray"
                className="!rounded-default !bg-input-gray"
                bordered={false}
                style={{ width: '100%', border: 'none' }}
                options={options}
                placeholder="请选择知识库"
                // multiple
                key={'key'}
                maxTagCount="responsive"
                showCheckedStrategy={SHOW_CHILD}
                // displayRender={displayRender}
                showSearch={{ filter }}
                popupClassName="share-link-modal-dropdown"
                onChange={(value, selectedOptions) => {
                  console.log('111111111111111', value, selectedOptions);

                  if (!value || !selectedOptions || selectedOptions.length === 0) {
                    form.setFieldsValue({ datasetId: undefined });
                    return;
                  }

                  const lastSelected = selectedOptions[selectedOptions.length - 1];

                  if (lastSelected?.type === 'folder') {
                    console.log('isFolder');

                    messageApi.open({
                      type: 'warning',
                      content: '请选择知识库',
                    });

                    // 双重保障：立即清空并阻止后续操作
                    form.setFieldsValue({ datasetId: [] });
                    return;
                  }

                  // 只有有效选择才更新表单
                  form.setFieldsValue({ datasetId: value });
                }}
              />
            </Form.Item>

            {radioValue === 'api' && datasetCreateType === 'metadata' && (
              <Form.Item label="请输入需要使用的metadata字段" name="datasetNameMetadata">
                <Input placeholder="请输入或粘贴（多个字段用,隔开）" className="!bg-input-gray" />
              </Form.Item>
            )}

            <Form.Item
              label="名称"
              name="name"
              rules={[
                { required: true, message: '请输入名称' },
                { whitespace: true, message: '名称不能仅为空格' },
              ]}
            >
              <Input
                className="!bg-input-gray"
                style={{ border: 'none' }}
                placeholder="请输入连接器名称，以使后期分辨"
              />
            </Form.Item>
          </Form>
        </div>
      </Modals>
    </>
  );
};

export default connectorAddModal;
